package controllers

import (
	"qkcoupon/db"
	"qkcoupon/errorcode"
	"qkcoupon/models"
	"qkcoupon/utils"
	"time"

	"encoding/json"

	"qkcoupon/rpc/client/qingke"

	log "github.com/cihub/seelog"
)

type ReceiveExchangeController struct {
	LoginedController
}

/*
 *@note  验证请求参数
 *@return (string, int64): (推荐者ID, 错误码)
 */
func (p *ReceiveExchangeController) verification() (string, uint) {
	errCode := errorcode.EC_GL_SUCCESS
	uid := ""
	for {
		uid = p.GetString("uid")
		if uid == "" {
			log.Warn("uid==''")
			errCode = errorcode.EC_GL_INTERNAL_ERROR
			break
		}

		break
	}
	return uid, errCode
}

type ReceiveExchangeReq struct {
	Code string `json:"code"`
}

// ReceiveExchange 接受优惠码的接口
// @router /receive [post]
func (p *ReceiveExchangeController) ReceiveExchange() {
	defer p.Output("ReceiveExchange")
	p.Resp["code"] = errorcode.EC_GL_SUCCESS

	data := p.Ctx.Input.RequestBody
	if len(data) == 0 {
		log.Warn("len(data)==0")
		p.Resp["code"] = errorcode.EC_GL_INTERNAL_ERROR
		return
	}

	log.Debug(string(data))

	req := &ReceiveExchangeReq{}
	err := json.Unmarshal(data, req)
	if err != nil {
		p.Resp["code"] = errorcode.EC_GL_INTERNAL_ERROR
		return
	}

	text := req.Code
	if !utils.CheckExchangeText(text) {
		p.Resp["code"] = errorcode.EC_QKCOUPON_INVALID_EXHCANGE_TEXT
		return
	}

	uid, errcode := p.verification()
	if errcode != errorcode.EC_GL_SUCCESS {
		p.Resp["code"] = errcode
		return
	}

	status, isExist, err2 := db.GetExchangeCode(text)
	if err2 != nil {
		p.Resp["code"] = errorcode.EC_GL_INTERNAL_ERROR
		return
	}

	if !isExist {
		p.Resp["code"] = errorcode.EC_QKCOUPON_INVALID_EXHCANGE_TEXT
		return
	}

	if status.CouponLimit > 0 {
		// 如果已抢完，返回
		if status.CouponCount >= status.CouponLimit {
			p.Resp["code"] = errorcode.EC_QKCOUPON_COUPON_GRAB_END
			return
		}
	}

	// 检查是否只对新用户有效
	if status.NewUserOnly {
		ak := p.GetString("ak")
		isNew, errcNew := qingke.CheckNewUser(ak, uid)
		if errcNew != errorcode.EC_GL_SUCCESS {
			log.Warnf("%d", errcNew)
		}
		if !isNew {
			p.Resp["code"] = errorcode.EC_QKCOUPON_ALREADY_OLD_USER
			return
		}
	}

	if status.UserLimit > 0 {
		if !db.CheckUserExchangeCount(status.ExchangeID, uid, status.UserLimit) {
			p.Resp["code"] = errorcode.EC_QKCOUPON_EXCHANGE_GRAB_END
			return
		}
	}

	if status.CouponLimit > 0 {
		ok, err3 := db.GrabExchangeWithLimit(status.ExchangeID)
		if err3 != nil {
			p.Resp["code"] = errorcode.EC_GL_INTERNAL_ERROR
			return
		}
		if !ok {
			p.Resp["code"] = errorcode.EC_QKCOUPON_COUPON_GRAB_END
			return
		}
	} else {
		err3 := db.GrabExchangeWithoutLimit(status.ExchangeID)
		if err3 != nil {
			p.Resp["code"] = errorcode.EC_GL_INTERNAL_ERROR
			return
		}
	}

	rulesJSON, err4 := db.GetExchangeRule(status.ExchangeID)
	if err4 != nil {
		p.Resp["code"] = errorcode.EC_GL_INTERNAL_ERROR
		return
	}
	if rulesJSON == "" {
		p.Resp["code"] = errorcode.EC_GL_INTERNAL_ERROR
		return
	}
	rules := &models.PSQkCouponExchangeRuleList{}
	err5 := json.Unmarshal([]byte(rulesJSON), rules)
	if err5 != nil {
		p.Resp["code"] = errorcode.EC_GL_INTERNAL_ERROR
		return
	}

	// 有效期包括当天，共七天
	now := time.Now().Unix()
	startTime := now - now%86400 - 3600*8
	endTime := startTime + 7*86400 - 60

	for _, rule := range rules.List {
		couponRule := p.ruleToCouponRule(rule)
		cid, errcode2 := db.CreateCoupon(couponRule, startTime, endTime, 0)
		if errcode2 != errorcode.EC_GL_SUCCESS {
			p.Resp["code"] = errcode2
			return
		}
		ccode, errcode3 := db.DispatchCouponForCcode(cid, uid)
		if errcode3 != errorcode.EC_GL_SUCCESS {
			p.Resp["code"] = errcode3
			return
		}
		err6 := db.RecordReceiveExchange(status.ExchangeID, uid, cid, ccode)
		if err6 != nil {
			p.Resp["code"] = errorcode.EC_GL_INTERNAL_ERROR
			return
		}
	}

	rerr := db.RecordUserExchange(status.ExchangeID, uid)
	if rerr != nil {
		p.Resp["code"] = errorcode.EC_GL_INTERNAL_ERROR
		return
	}

	p.Resp["list"] = rules.List
}

func (p *ReceiveExchangeController) ruleToCouponRule(rule *models.PSQkCouponExchangeRule) *models.PSQkCouponCreateCouponReq {
	couponRule := &models.PSQkCouponCreateCouponReq{}
	couponRule.Bid = rule.Bid
	couponRule.Ctype = rule.Ctype
	couponRule.Discount = rule.Discount
	couponRule.Lmode = rule.Lmode
	couponRule.MaxDiscount = rule.MaxDiscount
	couponRule.Rwids = rule.Rwids
	couponRule.Sum = rule.Sum
	couponRule.Utype = int32(models.EQKCOUPON_UTYPE_EXCHANGE_CODE_USER)
	return couponRule
}
